// import { verifyUploadPermiss } from './index';
import { getFullDate, storage } from '../tools'
import { OSS_ACCESS_KEY_ID, UPLOAD_SIGN, UPLOAD_POLICY, UPLOAD_EXPIRE, TUploadCategory } from '../../constants';


//设置上传到oss中的文件名
function setOSSUploadFileName(file: File | Blob, category: TUploadCategory) {
  let key = '', //存储到oss中的文件名
    picExtName = getExtName(file.type), // 获取文件后缀
		timeStamp = Date.now(), //获取13位时间戳
		randomSix = Math.random().toString().slice(-6); //获取6位随机数

	switch (category) {
		case '':
		case 'id': //身份证
			if (category === '') {
				key = `id/${getFullDate()}/id-front-` + timeStamp + '-' + randomSix + '.' + picExtName;
			} else {
				key = `id/${getFullDate()}/id-back-` + timeStamp + '-' + randomSix + '.' + picExtName;
			}
			break;
		case 'voucher':	//订单发票
		case 'license': //营业执照
		case 'remittance': //还款凭证
		case 'face': //人脸识别
		case 'contract': //合同
			key = `${category}/${getFullDate()}/${category}-` + timeStamp + '-' + randomSix + '.' + picExtName;
			break;
		default:
			break;
	}
	return key;
}


function getExtName(type: string = 'image/png') {
  const arr = type.split('/')
  return arr[1]
}

// 设置上传数据
export async function setUploadData(file: File | Blob, category: TUploadCategory): Promise<[FormData, string]> {
	const expireTime = Number(storage.get(UPLOAD_EXPIRE)) || 0
  if(Date.now() > expireTime) { // 如果过期要重新获取一次
    // const r = await verifyUploadPermiss()
  }
  const key = setOSSUploadFileName(file, category) // 设置文件名
  const fd = new FormData()
  fd.append('key', key)
  fd.append('policy', storage.get(UPLOAD_POLICY))
	fd.append('OSSAccessKeyId', storage.get(OSS_ACCESS_KEY_ID))
	fd.append('success_action_status', '200')
  fd.append('signature', storage.get(UPLOAD_SIGN))
	fd.append('file', file)
  return [fd, key]
}
